﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using MongoDB.Bson;
using MongoDB.Driver;
using DailyPhoto.EXIF;
using DailyPhoto.Common;

namespace DailyPhoto.Entities
{
    public abstract class Photo
    {
        public abstract void SaveFile(string filename);

        public abstract string PhotoId { get; set; }

        public string RepositoryName { get; set; }
    }


    public class FBPhoto : Photo
    {
        public FBPhoto(string pid)
        {
            this.PhotoId = pid;
        }
        
        public override string PhotoId { get; set; }

        public override void SaveFile(string filename)
        {
            var accessToken = Application.Config.accessToken.ToString();

            var photoQuery =
                    "https://graph.facebook.com/fql?q=SELECT+images+FROM+photo+WHERE+pid={0}&access_token={1}";

            using (var wc = new WebClient())
            {
                var jPhoto =
                wc.DownloadString(string.Format(photoQuery, this.PhotoId, accessToken));

                var json = JObject.Parse(jPhoto);

                var source = json["data"][0]["images"][0]["source"].ToString();

                wc.DownloadFile(source, filename);
            }
        }
    }

    public class FSPhoto : Photo
    {
        public FSPhoto(string original)
        {
            this.OriginalPath = original;
            this.Faces = new List<Faces.Face>();
        }

        public ObjectId Id { get; set; }

        public string OriginalPath { get; private set; }

        public override string PhotoId { get { return this.OriginalPath; } set { this.OriginalPath = value; } }

        public override void SaveFile(string filename)
        {
            var origin = new Bitmap(this.OriginalPath);;

            var exif = new EXIFextractor(ref origin, "n");

            RotateFlipType? flip = null;

            if (exif["Orientation"] != null)
            {
                flip = Util.OrientationToFlipType(exif["Orientation"].ToString());
            }

            if (origin.Height >= 800 || origin.Width >= 600)
            {
                var newImg =
                    Util.ScaleImage(origin, 800, 600);

                origin.Dispose();
                origin = new Bitmap(newImg);
            }


            if (flip.HasValue && flip.Value != RotateFlipType.RotateNoneFlipNone)
            {
                origin.RotateFlip(flip.Value);
            }

            origin.Save(filename, ImageFormat.Jpeg);
            origin.Dispose();

        }

        public IEnumerable<Faces.Face> Faces { get; set; }
        public int TotalFaces { get { return Faces == null ? 0 : Faces.Count(); } }
    }
}
